const router = require('express').Router();
const mongoose = require('mongoose');
const DictionaryModel = mongoose.models['Dictionary'];
const CompanyModel = mongoose.models['Company'];

router.get('/get', async function (req, res, next) {
    try{
        let company=await CompanyModel.findOne({weChatUserId:req.query._id});
        let result={};
        result.company=company;
        let dic=await DictionaryModel.findOne({key:'省市区'});
        result.provinces=dic.toVantJson();
        res.data(result);
    }catch(e){
        next(e.message);
    }
});

router.post('/save', async function (req, res, next) {
    try{
        let company=await CompanyModel.findOne({weChatUserId:req.body._id});
        req.body.weChatUserId=req.body._id;
        delete req.body._id;
        if(!company){
            await CompanyModel.create(req.body);
        }else{
            Object.assign(company,req.body);
            await company.save();
        }
        res.data(true);
    }catch(e){
        next(e.message);
    }
});

module.exports = router;